global nome, pathToFile, p1, ext

--property pdf : «constant ****PDF »
--property jpg : «constant ****JPEG»
on clicked theObject
	
	
	
	
	set this_file to choose file with prompt "Escolha a imagem" of type {"PDF", "com.adobe.pdf", "BMP", "com.microsoft.bmp", "JPEG", "JPEG2", "jpg", "public.jpeg", "PICT", "com.apple.pict", "PNG", "public.png", "PSD", "com.adobe.photoshop-image", "TIFF", "public.tiff"}
	set the target_length to 400
	try
		tell application "Image Events"
			-- start the Image Events application
			launch
			-- open the image file
			set this_image to open this_file
			-- get dimensions of the image
			copy dimensions of this_image to {W, H}
			-- determine the shortest side and then
			-- calculate the new length for the longer side
			if W is less than H then
				set the scale_length to (H * target_length) / W
				set the scale_length to ¬
					round scale_length rounding as taught in school
			else
				set the scale_length to (W * target_length) / H
				set the scale_length to ¬
					round scale_length rounding as taught in school
			end if
			-- perform action
			scale this_image to size scale_length
			-- save the changes
			
			set ext to file type of this_image
			if ext = PDF then
				set ext to ".pdf"
			else if ext = JPEG then
				set ext to ".jpg"
			else if ext = PNG then
				set ext to ".png"
			else if ext = PICT then
				set ext to ".pict"
			else if ext = TIFF then
				set ext to ".tif"
			else if ext = PSD then
				set ext to ".psd"
			else if ext = BMP then
				set ext to ".bmp"
			end if
			
			set pathToFile to (path to application support folder from user domain) as string
			set pathToFile to pathToFile & "PrePress:imagens:" as string
			set nome to random number
			set nome to nome as string
			set AppleScript's text item delimiters to "."
			set nome to nome's text item -1
			set AppleScript's text item delimiters to ""
			set nome to nome & ext --& ".pdf" 
			
			
			set p1 to (pathToFile & nome)
			save this_image in file p1 with icon
			-- purge the open image data
			close this_image
		end tell
	on error error_message
		display dialog error_message
	end try
	set nObra to get contents of text field "nObra" of window "Prepress Ver Obras"
	tell user defaults
		set theDatabaseFinal to contents of default entry "theDatabaseFinal"
	end tell
	
	set theDatabase to space & theDatabaseFinal & space
	set theDatabase to "sqlite3" & theDatabase & quote
	set changes to "update prepress set pathImagem = '" & p1 & "' where nObra='" & nObra & "'; "
	do shell script theDatabase & changes & quote
	
	
	set getImage to "select pathImagem from prepress where nObra='" & nObra & "';"
	set theImage to (do shell script theDatabase & getImage & quote)
	set theImage to theImage as alias
	set image of image view "previewImagem" of tab view item "outros" of tab view "tabObras" of window "PrePress Ver Obras" to load image theImage
end clicked

on will close theObject
	(*Add your script here.*)
end will close
